package com.example.boot.security;

import cn.hutool.json.JSONUtil;
import com.example.common.Result;
import com.example.utils.WebUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权失败和认证失败的处理器
 *
 * @author ding
 * @since 2024/7/23
 */
@Component
public class SecurityHandler {

    //授权失败
    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return (request, response, accessDeniedException) -> {
            Result result = Result.error("403","您的权限不足");
            String json = JSONUtil.toJsonStr(result);
            //将字符串渲染到客户端
            WebUtils.renderString403(response, json);
        };
    }

    //认证失败
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, authException) -> {
            Result result = Result.error("401", "认证失败，请重新登录");
            String json = JSONUtil.toJsonStr(result);
            WebUtils.renderString401(response, json);
        };
    }

}
